package online.heycm.rbac.common.config.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import online.heycm.rbac.common.config.RequestContext;
import online.heycm.rbac.common.entity.Session;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * 字段字段注入
 *
 * @author hey
 * @version 1.0
 * @date 2024/1/11 11:41
 */
public class AutoFillHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createdAt", Date.class, new Date());
        Session session = RequestContext.get();
        if (session != null) {
            this.strictInsertFill(metaObject, "createdBy", Integer.class, session.getUserId());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updatedAt", Date.class, new Date());
        Session session = RequestContext.get();
        if (session != null) {
            this.strictUpdateFill(metaObject, "updatedBy", Integer.class, session.getUserId());
        }
    }
}
